<template>
  <div class="contanier" @click="cleanEdit">
    <div class="table-wrapper">
      <div>
        <el-button
          class="el-icon-circle-plus"
          @click="addColumn"
          v-if="addColumns && limit > changeColumns.length"
          >添加列</el-button
        >
      </div>

      <div style="overflow-x: auto">
        <el-table
          :data="tableData"
          :show-header="false"
          style="width: 100%"
          :border="false"
        >
          <el-table-column
            v-for="(item, index) in changeColumns"
            :key="index"
            :prop="item.key"
            width="180px"
          >
            <template slot-scope="scope">
              <div
                class="table-item"
                @click.stop="handleClick(scope.row, item.key, scope.$index)"
                @mouseover="handleMouseOver(scope.$index, item.key)"
                @mouseleave="handleMouseLeave(scope.$index, item.key)"
              >
                <template
                  v-if="
                    editingRow === scope.$index &&
                    item.key === editingColumn &&
                    !(addRows && scope.$index == 0) &&
                    !(addColumns && index == 0)
                  "
                >
                  <el-input
                    class="input"
                    v-model="scope.row[item.key]"
                    @blur="finishEdit(scope.row, item.key)"
                    @input="handleInput($event, scope.$index, index)"
                  />
                </template>
                <template v-else>
                  <div :class="scope.$index === 0 ? 'title' : 'content'">
                    {{ scope.row[item.key] }}
                  </div>
                  <div
                    v-if="
                      deleteRow === scope.$index &&
                      deleteColumn.length > 0 &&
                      deleteColumn === item.key &&
                      ((scope.row === tableData[0] && index !== 0) ||
                        (item.key === 'column0' && scope.$index !== 0)) &&
                      !(addRows && scope.$index == 0) &&
                      !(addColumns && index == 0)
                    "
                    class="el-icon-error delete"
                    @click="
                      scope.row === tableData[0]
                        ? deleteColumns(index)
                        : deleteRows(scope.$index)
                    "
                  ></div>
                </template>
              </div>
            </template>
          </el-table-column>
        </el-table>
        <div>
          <el-button
            class="el-icon-circle-plus"
            @click="addRow"
            v-if="addRows && limit > tableData.length"
            >添加行</el-button
          >
        </div>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: "editorTable",
  props: {
    columns: {
      type: Array,
      default: () => [{ key: "column0" }],
    },
    rows: {
      type: Array,
      default: () => [{ column0: "" }],
    },
    addRows: {
      type: Boolean,
      default: false,
    },
    addColumns: {
      type: Boolean,
      default: false,
    },

    keyList: {
      type: Array,
      default: () => ["realmName", "realmValue"],
    },
    limit: {
      type: Number | String,
      default: 1000,
    },

    rules: {
      type: Array,
      default: () => [
        { type: "TEXT", before: 5, after: 2,number:100 },
        { type: "TEXT", before: 6, after: 2,number:100 },
      ],
    },
  },
  data() {
    return {
      // 其他初始数据行
      tableData: this.rows,
      // 其他初始列
      changeColumns: this.columns,
      editingColumn: null,
      editingRow: null,
      editingModel: null,
      deleteColumn: "",
      deleteRow: -1,
    };
  },

  watch: {
    rows: {
      handler(newValue, oldValue) {
        this.tableData = newValue;
      },
      deep: true, // 监视对象或数组内部值的变化
    },

    columns: {
      handler(newValue, oldValue) {
        this.changeColumns = newValue;
      },
      deep: true, // 监视对象或数组内部值的变化
    },
  },
  computed: {
    //输出结果
    formartTableData() {
      if (this.addColumns) {
        return this.formartColumnData();
      }
      if (this.addRows) {
        return this.formartRowsData();
      }
      return this.tableData;
    },
  },
  methods: {
    addColumn() {
      let lastObj = this.changeColumns[this.changeColumns.length - 1];
      let num = Number(lastObj.key.replace("column", ""));
      let newKey = `column${num + 1}`;
      this.changeColumns.push({
        key: newKey,
      });
      this.tableData.forEach((item) => {
        this.$set(item, newKey, "");
      });
    },
    addRow() {
      let lastObj = this.tableData[this.tableData.length - 1]; // 创建一个新的空对象
      var newObj = Object.assign({}, lastObj);
      for (var key in newObj) {
        newObj[key] = "";
      }

      this.tableData.push(newObj);
    },
    handleClick(row, key, index) {
      if (this.editingModel && this.editingRow !== index) {
        this.finishEdit(this.editingModel, this.editingColumn);
      }
      // row.isEdit = true;
      this.editingColumn = key;
      this.editingRow = index;
      this.editingModel = row;
    },
    handleMouseOver(index, key) {
      this.deleteColumn = key;
      this.deleteRow = index;
    },
    handleMouseLeave() {
      this.deleteColumn = "";
      this.deleteRow = -1;
    },
    finishEdit(row, key) {
      // row.isEdit = false;
      this.editingColumn = null;
      this.editingRow = null;
      this.editingModel = null;
      this.$nextTick(() => {
        // 更新数据
        this.$set(row, key, row[key]);
      });
    },
    cleanEdit() {
      this.editingColumn = null;
      this.editingRow = null;
      this.editingModel = null;
    },

    deleteColumns(index) {
      this.tableData.forEach((item) => {
        this.$delete(item, this.changeColumns[index].key);
      });
      this.changeColumns.splice(index, 1);
    },

    deleteRows(index) {
      this.tableData.splice(index, 1);
    },

    formartColumnData() {
      let arr = [];
      for (let i = 0; i < this.changeColumns.length; i++) {
        const params = {};
        let key = this.changeColumns[i].key;
        for (let index = 0; index < this.keyList.length; index++) {
          let subKey = this.keyList[index];
          let item = this.tableData[index];
          params[subKey] = item[key];
        }
        arr.push(params);
      }

      arr.splice(0, 1);
      return arr;
    },

    formartRowsData() {
      let arr = [];
      for (let index = 0; index < this.tableData.length; index++) {
        const params = {};
        let item = this.tableData[index];
        for (let i = 0; i < this.changeColumns.length; i++) {
          let key = this.changeColumns[i].key;
          let subK = this.keyList[i];
          params[subK] = item[key];
        }
        arr.push(params);
      }

      arr.splice(0, 1);
      return arr;
    },

    maxLength(row, column) {
      if (row == 0 || column == 0) {
        return 5;
      }
      return 6;
    },

    handleInput(value, row, column) {
      let reg;
      let a = "TEXT";
      let before = 100;
      let after = 100;
      let number = 10;
      if (this.addRows) {
        a = this.rules[column].type;
        before = this.rules[column].before;
        after = this.rules[column].after;
        number = this.rules[column].number;
      } else {
        a = this.rules[row].type;
        before = this.rules[row].before;
        after = this.rules[row].after;
        number = this.rules[row].number;
      }

      if (a === "TEXT") {
        // 输入为整数，最多number位
        if (value.length > before) {
          this.tableData[this.editingRow][this.editingColumn] = value.substring(
            0,
            before
          );
        }
      } else {
        if (a === "INTEGER") {
          // 输入为整数，最多number位
          reg = new RegExp("^\\d{0," + before + "}", "g");
        }
        if (a === "DECIMAL") {
          before--;
          // 输入为小数，前before以及后after
          reg = new RegExp(
            "^(\\-|\\+)?(([1-9]{0,1}\\d{0," +
              before +
              "})|(0{1}))(\\.\\d{0," +
              after +
              "})?",
            "g"
          );
        }

        if (a === 'IOD') {
        // 校验是否包含小数点 如果包含的情况下走整数、不包含的情况下走小数
        if (value.indexOf("\.") === -1) {
          // 不包含
          reg = new RegExp("^\\d{1," + number + "}$");
        } else {
          reg = new RegExp("^(\\-)?\\d{1," + before + "}(\\.\\d{1," + after + "})$");
        }
      }
        this.tableData[this.editingRow][this.editingColumn] =
          value.match(reg)[0];
      }
    },
  },
};
</script>

<style scoped lang="less">
.contanier {
  .table-wrapper {
    display: flex;
    flex-direction: column;

    .add-column-button {
      width: 40px;
      height: 40px;
    }

    .title {
      font-size: 14px;
      font-family: PingFangSC-Medium, PingFang SC;
      font-weight: 600;
      color: #292830;
      line-height: 22px;
    }

    .el-table::before {
      z-index: inherit; // 规定应该从父元素继承 z-index 属性的值。
    }

    ::v-deep .el-table td.el-table__cell,
    .el-table th.el-table__cell.is-leaf {
      border: 1px solid #dddfe6;
    }
    ::v-deep .el-table--border::after,
    .el-table--group::after,
    .el-table::before {
      border: #dddfe6;
    }
    .table-item {
      min-width: 150px;
      min-height: 40px;
      display: flex;
      align-items: center;
      justify-content: center;
      position: relative;
      text-align: center;
      .input {
        width: 120px;
      }

      .delete {
        position: absolute;
        right: 10px;
        top: 12px;
        width: 20px;
        height: 20px;
        // margin-left: 20px;
      }
    }
  }
}
</style>
